﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Reflection.Emit;
using System.Reflection;
using System.Collections.Generic;
using SPPivotViewer.Utility;

// Thank to F.Rodriguez http://franpoint.blogspot.com/2012/01/modifying-pivot-viewer-for-sharepoint.html


namespace SPPivotViewer.SPPivotViewerWP
{

    [ToolboxItemAttribute(false)]
    public class SPPivotViewerWP : WebPart
    {
        private string _pivotviewerXapUrl;
        public string XapUrl
        {
            get { return _pivotviewerXapUrl; }
            set { _pivotviewerXapUrl = value; }
        }


        private bool _windowless;
        public bool WindowLess
        {
            get { return _windowless; }
            set { _windowless = value; }
        }


        private string _strType;

        public string Type
        {
            get { return _strType; }
            set { _strType = value; }
        }

        private string _strListName;

        public string ListName
        {
            get { return _strListName; }
            set { _strListName = value; }
        }
        private string _strFieldDisplay;

        public string FieldDisplay
        {
            get { return _strFieldDisplay; }
            set { _strFieldDisplay = value; }
        }

        private string _strFieldImage;

        public string FieldImage
        {
            get { return _strFieldImage; }
            set { _strFieldImage = value; }
        }
        private string _strURLImageSubstitue;

        public string URLImageSubstitue
        {
            get { return _strURLImageSubstitue; }
            set { _strURLImageSubstitue = value; }
        }
        private string _strFieldUrl;

        public string FieldUrl
        {
            get { return _strFieldUrl; }
            set { _strFieldUrl = value; }
        }

        private int _iItemOpen;

        public int ItemOpen
        {
            get { return _iItemOpen; }
            set { _iItemOpen = value; }
        }

        private string _strInfos;

        public string Infos
        {
            get { return _strInfos; }
            set { _strInfos = value; }
        }

        private string _strARGBFilter;

        public string ARGBFilter
        {
            get { return _strARGBFilter; }
            set { _strARGBFilter = value; }
        }

        private string _strURLFilter;

        public string URLFilter
        {
            get { return _strURLFilter; }
            set { _strURLFilter = value; }
        }

        private string _strARGBInfo;

        public string ARGBInfo
        {
            get { return _strARGBInfo; }
            set { _strARGBInfo = value; }
        }

        private string _strURLInfo;

        public string URLInfo
        {
            get { return _strURLInfo; }
            set { _strURLInfo = value; }
        }

        private string _strARGBTitle;

        public string ARGBTitle
        {
            get { return _strARGBTitle; }
            set { _strARGBTitle = value; }
        }

        private string _strURLTitle;

        public string URLTitle
        {
            get { return _strURLTitle; }
            set { _strURLTitle = value; }
        }

        private string _strARGBContent;

        public string ARGBContent
        {
            get
            {
                return _strARGBContent;

            }
            set
            {
                _strARGBContent = value;
            }
        }

        private string _strURLContent;

        public string URLContent
        {
            get { return _strURLContent; }
            set { _strURLContent = value; }
        }

        private bool _bHideTitle;

        public bool HideTitle
        {
            get { return _bHideTitle; }
            set { _bHideTitle = value; }
        }

        private bool _bHideInfo;

        public bool HideInfo
        {
            get { return _bHideInfo; }
            set { _bHideInfo = value; }
        }

        private bool _bHideFilter;

        public bool HideFilter
        {
            get { return _bHideFilter; }
            set { _bHideFilter = value; }
        }

        private int _iBaseList;

        public int BaseList
        {
            get
            {
                return _iBaseList;
            }
            set
            {
                _iBaseList = value;
            }
        }

        private string _strStretchContent;

        public string StretchContent
        {
            get { return _strStretchContent; }
            set { _strStretchContent = value; }
        }
        private string _strStretchTitle;

        public string StretchTitle
        {
            get { return _strStretchTitle; }
            set { _strStretchTitle = value; }
        }
        private string _strStretchFilter;

        public string StretchFilter
        {
            get { return _strStretchFilter; }
            set { _strStretchFilter = value; }
        }
        private string _strStretchInfo;

        public string StretchInfo
        {
            get { return _strStretchInfo; }
            set { _strStretchInfo = value; }
        }
        public override EditorPartCollection CreateEditorParts()
        {
            List<EditorPart> lstEditorPart = new List<EditorPart>();
            EditorCollectionPivotViewer epv = new EditorCollectionPivotViewer();
            epv.ID = this.ID + "_EditorCollectionPart";
            lstEditorPart.Add(epv);

            EditorUIPivotViewer epui = new EditorUIPivotViewer();
            epui.ID = this.ID + "_EditorUIPart";
            lstEditorPart.Add(epui);
            
            EditorPartCollection epc = base.CreateEditorParts();
            return new EditorPartCollection(epc, lstEditorPart);
        }
        protected override void CreateChildControls()
        {
            if (string.IsNullOrEmpty(_strType))
            {
                string strhtml = "<h2>You need to configure webpart by edit webpart and set List</h2>";
                this.Controls.Add(new LiteralControl(strhtml));

                return;
            }
            if (this.WebPartManager.DisplayMode == WebPartManager.EditDisplayMode)
            {
                string strhtml = "<h2>Silverlight Rendering is disable in Design Mode</h2>";
                this.Controls.Add(new LiteralControl(strhtml));

                return;
            }

            if (_strFieldDisplay == null)
                _strFieldDisplay = "";


            string strUrlSilverlight = ProcessXapUrl(XapUrl);

            
            string strUrlCXML = string.Format(SPContext.Current.Web.Url + "/" + this.ListName.Replace(" ", "%20") + ".cxml");
            string strUrlProfile = string.Format(SPContext.Current.Web.Url + "/UserProfileCollection.cxml");
            string strUrlWebNavigation = string.Format(SPContext.Current.Web.Url + "/AllWebNavigationCollection.cxml");
            string strUrlSearch = string.Format(SPContext.Current.Web.Url + "/SearchPivot.cxml?k=" + this.Page.Request.QueryString["k"]);
            string strUrlSiteData = string.Format(SPContext.Current.Web.Url + "/SiteDataQueryFactory.cxml?listbase={0}", _iBaseList);
            string strInitParamsValue;

            if (Type == "List")
                strInitParamsValue = "cxml=" + strUrlCXML + ",itemOpen=" + _iItemOpen + ",Facets=" + _strFieldDisplay + ",Infos=" + _strInfos + ",ImageField=" + _strFieldImage + ",ImageSubstitue=" + _strURLImageSubstitue + ",FieldUrl=" + _strFieldUrl;
            else if (Type == "User Profile")
                strInitParamsValue = "cxml=" + strUrlProfile + ",Facets=" + _strFieldDisplay + ",Infos=" + _strInfos;
            else if (Type == "Search")
                strInitParamsValue = "cxml=" + strUrlSearch;
            else if (Type == "Site Collection Data")
                strInitParamsValue = "cxml=" + strUrlSiteData;
            else
                strInitParamsValue = "cxml=" + strUrlWebNavigation;

            if (PV4SPSettings.GetValue(SPContext.Current.Web, PV4SPSettings.cstUI).Equals(bool.TrueString))
                strInitParamsValue += BuildUIParameter();


            string strInitParams = string.Format("<param name=\"initParams\" value=\"{0}\" />", strInitParamsValue);
            string strSilverlight = " <object id=\"pivotViewer\" data=\"data:application/x-silverlight-2,\" type=\"application/x-silverlight-2\" width=\"100%\" height=\"90%\">" +
                (WindowLess ? "<param name=\"WindowLess\" value=\"true\" />" : "") +
                "<param name=\"source\" value=\"" + strUrlSilverlight + "\"/>" +
                "<param name=\"onError\" value=\"onSilverlightError\" />" +
                "<param name=\"background\" value=\"white\" />" +
                "<param name=\"minRuntimeVersion\" value=\"4.0.50401.0\" />" +
                "<param name=\"autoUpgrade\" value=\"true\" />" +
                strInitParams +
                "<a href=\"http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50401.0\" style=\"text-decoration:none\">" +
                "<img src=\"http://go.microsoft.com/fwlink/?LinkId=161376\" alt=\"Get Microsoft Silverlight\" style=\"border-style:none\"/></a></object>";
            this.Controls.Add(new LiteralControl(strSilverlight));

        }

        private string ProcessXapUrl(string xapUrl)
        {
            if (xapUrl.ToLower().StartsWith("http"))
            { //Absolute URL
                return xapUrl;
            }
            else if (xapUrl.StartsWith("/"))
            { //Site collection relative url
                return SPContext.Current.Site.Url + xapUrl;
            }
            else if (!string.IsNullOrEmpty(xapUrl))
            { //Site relative url
                return SPContext.Current.Web.Url + "/" + xapUrl;
            }
            else
            {
                return Page.ClientScript.GetWebResourceUrl(typeof(SPPivotViewer.SPPivotViewerWP.SPPivotViewerWP), "SPPivotViewer.SPPivotViewerWP.SLPivotViewer.xap");
            }
        }

        private bool fromArrayColortoStringColor(string[] strArray, int length, out string strOut)
        {
            strOut = null;
            if (strArray == null || strArray.Length != length)
                return false;
            strOut = string.Join("|", strArray);
            return true;
        }
        private bool arrayToStringColor(string aColor, out string strColor)
        {
            strColor = null;
            if (aColor == null)
                return false;

            string[] argbColor = aColor.Split('|');
            if (argbColor.Length != 4)
                return false;
            bool bValid = true;
            foreach (string str in argbColor)
            {
                if (string.IsNullOrEmpty(str))
                {
                    bValid = false;
                    break;
                }
                int i = 0;
                if (!int.TryParse(str, out i))
                {
                    bValid = false;
                    break;
                }
                if (i < 0 || i > 255)
                {
                    bValid = false;
                    break;
                }

            }
            if (bValid)
            {
                strColor = string.Join("|", argbColor);
            }
            return bValid;
        }
        private string BuildUIParameter()
        {
            string strReturn = ",";
            string strOut = "";
            if (string.IsNullOrEmpty(_strURLContent) && arrayToStringColor(_strARGBContent, out strOut))
                strReturn += "ARGBContent=" + strOut + ",";
            if (!string.IsNullOrEmpty(_strURLContent))
                strReturn += "URLContent=" + _strURLContent + ",";

            if (string.IsNullOrEmpty(_strURLFilter) && arrayToStringColor(_strARGBFilter, out strOut))
                strReturn += "ARGBFilter=" + strOut + ",";
            if (!string.IsNullOrEmpty(_strURLFilter))
                strReturn += "URLFilter=" + _strURLFilter + ",";


            if (string.IsNullOrEmpty(_strURLInfo) && arrayToStringColor(_strARGBInfo, out strOut))
                strReturn += "ARGBInfo=" + strOut + ",";
            if (!string.IsNullOrEmpty(_strURLInfo))
                strReturn += "URLInfo=" + _strURLInfo + ",";

            if (string.IsNullOrEmpty(_strURLTitle) && arrayToStringColor(_strARGBTitle, out strOut))
                strReturn += "ARGBTitle=" + strOut + ",";
            if (!string.IsNullOrEmpty(_strURLTitle))
                strReturn += "URLTitle=" + _strURLTitle + ",";

            if (!string.IsNullOrEmpty(StretchTitle))
                strReturn += "StretchTitle=" + StretchTitle + ",";
            else
                strReturn += "StretchTitle=Fill,";


            if (!string.IsNullOrEmpty(StretchContent))
                strReturn += "StretchContent=" + StretchContent + ",";
            else
                strReturn += "StretchContent=Fill,";


            if (!string.IsNullOrEmpty(StretchInfo))
                strReturn += "StretchInfo=" + StretchInfo + ",";
            else
                strReturn += "StretchInfo=Fill,";


            if (!string.IsNullOrEmpty(StretchFilter))
                strReturn += "StretchFilter=" + StretchFilter + ",";
            else
                strReturn += "StretchFilter=Fill,";

            strReturn += "HideTitle=" + HideTitle + ",";
            strReturn += "HideInfo=" + HideInfo + ",";
            strReturn += "HideFilter=" + HideFilter + ",";
            return strReturn;
        }
    }
}
